<?php

namespace App\Services\ApplyDrinkProductOrder;

use Closure;
use App\Models\User;
use App\Models\Order;
use App\Models\Address;
use App\Models\Product;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplyDrinkProductOrderRequest extends FormRequest
{
    protected ?Address $address = null;

	public function rules(): array
	{
        $addressId =  (int)request('address_id');
        if ($addressId) {
            $this->address = Address::find($addressId);
        }

        $productId =  (int)request('product_id');
        if ($productId) {
            $this->product = Product::find($productId);
            $this->sku =  $this->product->skus()->first();
        }

        
		return [
			'product_id' => [
				'required',
				'integer',
                'min:1',
				$this->product(),
			],
			'address_id' => [
                'required',
				'integer',
                'min:1',
                $this->address(),
			],
			'attr' => [
                'required',
				'string',
                'min:1'
			]
		];
	}

	public function product()
	{
		return function ($attribute, $value, $fail) {

			if (!$sku = $this->sku) {
				return $fail('此商品不存在');
			} elseif (!$sku->product->is_sale) {
				return $fail('此商品未上架');
			} elseif (!$sku->product->is_drink) {
				return $fail('此商品不属于畅饮商品');
			} elseif ($sku->stock === 0) {
				return $fail('此商品已售完');
			} elseif ($sku->product->is_hongkong_direct
				or $sku->product->is_overseas_direct) {
				if (!$this->address->id_code) {
					return $fail('海外直邮商品提供收件人证件号码');
				}
			}
			
			$amount = 1;
			if ($amount > 0 and $amount > $sku->stock) {
				return $fail('此商品库存不足');
			}
			return true;
		};
	}

    public function address(): Closure
    {
        return function ($attribute, $value, $fail) {
            if (!$this->address) {
                return $fail('地址不存在');
            } elseif (!Order::isAddressSupported($this->address)) {
                return $fail('地址不在配送范围');
            }
            return true;
        };
    }

     


    public function getAddress(): Address
    {
        return $this->address;
    }

    public function getProduct(): Product
    {
        return $this->product;
    }
}
